/*
 * @Author: zhangyujie
 * @Date:   2015-08-12 10:43:00
 * @Last Modified by:   zhangyujie
 * @Last Modified time: 2015-08-14 16:16:45
 */

define(['jquery', 'd3','util','hammer','rose'], function($, d3,util,Hammer,productRing) {

	function singleBrokenLine(selector,selector_sub,data,url,url2) {
		var url2=url2;
		var setting = {
			selector: selector,
			series: {
				dataset:data,
				//dataset: [{
				//	'name': '2015-01',
				//	'value': 14
				//}, {
				//	'name': '2015-02',
				//	'value': 19
				//}, {
				//	'name': '2015-03',
				//	'value': 15
				//}, {
				//	'name': '2015-04',
				//	'value': 4
				//}, {
				//	'name': '2015-05',
				//	'value': 5
				//}, {
				//	'name': '2015-06',
				//	'value': 10
				//}, {
				//	'name': '2015-07',
				//	'value': 25
				//}, {
				//	'name': '2015-08',
				//	'value': 16
				//}, {
				//	'name': '2015-09',
				//	'value': 20
				//}, {
				//	'name': '2015-10',
				//	'value': 22
				//}, {
				//	'name': '2015-11',
				//	'value': 19
				//}, {
				//	'name': '2015-12',
				//	'value': 26
				//}, {
				//	'name': '2016-1',
				//	'value': 26
				//}, {
				//	'name': '2016-2',
				//	'value': 26
				//}, {
				//	'name': '2016-3',
				//	'value': 26
				//}],
				textStyle: {
					"font-size": '16px',
					'font-weight': 'bold',
					'fill': '#858586',
					'font-famliy': '微软雅黑'
				}
			},
			xAxis: {
				tickPadding: 10,
				rect: {
					height: 30,
					width: 350
				}
			},
			yAxis: {
				tickPadding: 10
			},
			radius: 4,
			colorset: ['#24D2FD', '#60AFF9', '#1989BB', '#2CB551', '#E6E747', '#F6B86D', '#FD8C84'],
			margin: {
				top: 30,
				right: 40,
				bottom: 30,
				left: 15
			}
		}
		four(setting)

		function four(setting) {
			var selector = setting.selector,
				series = setting.series,
				dataset = series.dataset,
				otherColor = setting.otherColor,
				colorset = setting.colorset,
				xSetting = setting.xAxis,
				ySetting = setting.yAxis,
				radius = setting.radius,
				margin = setting.margin,
				relcontentW = document.querySelector(selector).offsetWidth,
				height = document.querySelector(selector).offsetHeight,
				length = dataset.length,
				dom = document.querySelector(selector);



				dataset.forEach(function(e){
					e.value/=10000;
				})

			var svg,
				content,
				totalGroup,
				xScale,
				yScale,
				incomeGroup,
				circle,
				xAxis,
				yAxis,
				xAxisData = [],
				yAxisData = [],
				yMax,
				diff
			var format = d3.time.format("%Y-%m")
			for (var i = 0, tempData; tempData = dataset[i++];) {

				xAxisData.push(format.parse(tempData['name']))
			}

			if (xAxisData.length > 12) {
				var width = 1.5 * relcontentW
			} else {
				var width = relcontentW
			}
			var contentW = width - margin.left - margin.right,
				contentH = height - margin.top - margin.bottom
			yMax = d3.max(dataset, function(d, i) {
				return d['value']
			})

			diff = yMax / 10
			for (var i = 0; i < yMax; i += diff) {
				yAxisData.push(Number(i.toFixed(1)))
			}
			yAxisData.push(yMax)

			xScale = d3.time.scale()
				.domain(d3.extent(xAxisData), function(d) {
					return xAxisData
				})
				// .rangeRoundPoints([margin.left, width - margin.right])
				.range([0, contentW])


			yScale = d3.scale.linear()
				.domain([0, yMax])
				//.range([height - margin.bottom, margin.top])
				.range([contentH, 0])

			svg = d3.select(selector + " div").append('svg')
				.attr('width', width)
				.attr('height', height)
				.attr("class", "four")

			Ysvg = d3.select(selector).append('svg')
				.attr('width', width)
				.attr('height', height)
			content = svg.append('g')
				.attr('class', 'content')
				.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

			Ycontent = Ysvg.append('g')
				.attr('class', 'content')
				.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

			xAxis = d3.svg.axis()
				.scale(xScale)
				.tickValues(xAxisData)
				.tickPadding(xSetting.tickPadding)
				.orient('bottom')
				.tickSize(0)
			yAxis = d3.svg.axis()
				.scale(yScale)
				.tickValues(yAxisData)
				.orient('right')
				.tickSize(0)

			content.append('rect')
				.attr('x', 0)
				.attr('y', 0)
				.attr('fill', '#E3E3E3')
				.attr('width', width)
				.attr('height', xSetting['rect']['height'])
				.attr('transform', 'translate(' + (-margin.left) + ',' + (contentH) + ')')
			content.append('g')
				.attr('class', 'xAxis')
				.attr('transform', 'translate(' + 0 + ',' + (contentH) + ')')
				.call(xAxis)


			Ycontent.append('g')
				.attr('class', 'yAxis')
				.attr('transform', 'translate(' + (relcontentW - margin.left - margin.right) + ',' + 0 + ')')
				.call(yAxis)



			content.select('.yAxis .tick text')
				.remove()

			svg.selectAll('.xAxis .tick')
				.append('line')
				.attr('x1', 0)
				.attr('y1', 0)
				.attr('x2', 0)
				.attr('y2', -(contentH))
			Ycontent.selectAll('.yAxis .tick')
				.attr('opacity', function(d, i) {
					if (i == yAxisData.length - 1) {
						d3.select(this).append('line')
							.attr('x1', 0)
							.attr('y1', 0)
							.attr('x2', -(width - margin.left - margin.right))
							.attr('y2', 0)

					}
				})

			var brokeLinear = content.append('defs')
				.append('linearGradient')
				.attr('id', 'brokeArea')
				.attr('x1', '100%')
				.attr('y1', '100%')
				.attr('x2', '100%')
				.attr('y2', '0%')

			svg.append("clipPath")
				.attr("id", "content-brokeArea")
				.append("rect")
				.attr("x", -10)
				.attr("y", -10)
				.attr("height", height)
				.attr("width", "10")
				.transition()
				.duration(1000)
				.attr("width", width);

			brokeLinear.append('stop')
				.attr('offset', '0%')
				.style({
					'stop-color': '#DDEDFD',
					'stop-opacity': 0.5
				})

			brokeLinear.append('stop')
				.attr('offset', '25%')
				.style({
					'stop-color': '#84C6FF',
					'stop-opacity': 1
				})
			var area = d3.svg.area()
				.x(function(d, i) {
					return xScale(xAxisData[i])
				})
				.y0(height - margin.bottom - margin.top)
				.y1(function(d, i) {

					return yScale(d['value'])
				});
			var brokeArea = content.append('g')
				.attr('class', 'brokeArea')
				.attr("clip-path", "url(#content-brokeArea)")
			var pct = brokeArea.append("g")
				.attr("class", "pct")


			pct.append("path")
				.datum(dataset)
				.attr("fill", 'url(#brokeArea)')
				.attr("d", area)
				.style("opacity", "0.7")

			brokeArea.selectAll('circle')
				.data(dataset)
				.enter()
				.append('circle')
				.attr('class', 'circle')


				.attr('r', radius)
				.attr('cx', function(d, i) {
					return xScale(xAxisData[i])
				})
				.attr('cy', function(d, i) {
					return yScale(d['value'])
				})
				.attr('fill', '#fff')
				.attr('stroke', '#84C6FF')
				.attr('stroke-width', 1)

				.attr('mydate', function(d, i) {
					return d.name;

				})

			var lineWrap = content.append('g')
				.style('display', 'none')

			var rect = lineWrap.append("g")

			rect.append("rect")
				.attr("width", 40)
				.attr("height", 20)
				.attr("fill", '#ffc30e')
			rect.append("polygon")
				.attr("points", function(d, i) {
					return 0 + "," + 5 + " " + 40 + "," + 5 + " " + 20 + "," + 27
				})
				.attr("fill", "#ffc30e")
				// .attr("transform", "translate(" + margin.left + "," + (-26) + ")")
				// .attr("stroke", function(d, i) {
				// 	return colorset[i]
				// })
				// .attr("stroke-width", 1)
			rect.append("text")
				.attr("transform", "translate(" + 10 + "," + 18 + ")")
				.style("fill","#000")
				.style("font-size","16px")
				.attr("class","rectClass")
				.text("111")
			var line = lineWrap
				.append('line')
				.attr('x1', 0)
				.attr('y2', 0)
				.attr('x2', 0)
				.attr('y2', contentH)
				.attr('fill', '#ffc30e')
				.attr('stroke', '#ffc30e')


			var circleWrap = lineWrap
				.append('g')

			circleWrap.append('circle')
				.attr('r', 10)
				.attr('fill', '#fff')
				.attr('stroke-width', '2px')
				.attr('stroke', '#ffc30e')

			circleWrap.append('circle')
				.attr('r', 6)
				.attr('fill', '#ffc30e')


			for (var j = 0; j < xAxisData.length; j++) {
				d3.select(svg.selectAll('.xAxis text')[j])
					.text(function() {

						for (var i = 0; i < xAxisData.length; i++) {
							$(this[i]).attr("data",function() {
								return dataset[i].value
							})
							.attr("class","sinline")
							.attr("data-type",function() {
								return i
							})
							.attr("mydate",function() {
								return dataset[i].name
							})
							if (d3.select(this[i]).text() == "February") {
								d3.select(this[i]).text(2)
							} else if (d3.select(this[i]).text() == "March") {
								d3.select(this[i]).text(3)
							} else if (d3.select(this[i]).text() == "April") {
								d3.select(this[i]).text(4)
							} else if (d3.select(this[i]).text() == "May") {
								d3.select(this[i]).text(5)
							} else if (d3.select(this[i]).text() == "June") {
								d3.select(this[i]).text(6)
							} else if (d3.select(this[i]).text() == "July") {
								d3.select(this[i]).text(7)
							} else if (d3.select(this[i]).text() == "August") {
								d3.select(this[i]).text(8)
							} else if (d3.select(this[i]).text() == "September") {
								d3.select(this[i]).text(9)
							} else if (d3.select(this[i]).text() == "October") {
								d3.select(this[i]).text(10)
							} else if (d3.select(this[i]).text() == "November") {
								d3.select(this[i]).text(11)
							} else if (d3.select(this[i]).text() == "December") {
								d3.select(this[i]).text(12)
							}
						}
					})

				d3.select(svg.selectAll('.circle')[j])
					.text(function() {

						for (var i = 0; i < xAxisData.length; i++) {

							$(this[i]).attr("data-type", i)
							$(this[i]).attr("data",function() {
								return dataset[i].value
							})
						}
					})
			}
			content.selectAll(".xAxis text")
				.on('click', touch)

			content.selectAll(".circle")
				.on('click', touch)

			var hammertime = new Hammer(document.querySelector(".four"));
			//添加事件
			var cur = 0

			var ulWidth = width

			var two_3 = $(selector_sub).width()



			hammertime.on("pan", function(e) {


				cur += e.deltaX;

				if (cur * 0.2 > 0) {
					cur = 0;
					$(".four").css("margin-left", 0)

					return
				}
				if (cur * 0.2 < -ulWidth + two_3) {
					cur = (-ulWidth + two_3) / 0.2

					$(".four").css("margin-left", -ulWidth + two_3 +margin.left)

					return
				}

				$(".four").css("margin-left", cur * 0.2)
			})

			function touch() {


				var date=$(this).attr("mydate");

				$.ajax({
					url:url,
					async:false,
					data:{
						date:date
					},
					success: function(data){

						// console.log(data)
						if(data.status==1){

							var total=0;
							var available=[];
							data.data.forEach(function(d){
								total+= d.totalNum;
							});
							data.data.forEach(function(d){
								var tmp={"name": d.pName,
									"value": ((d.totalNum/total).toFixed(2))*100,
									"pId": d.pId,
									"date":date
								};
								available.push(tmp);

							});

							$("#seven1").empty();
							productRing.productRing("#seven1",available,url2);
						}
					}
				});

				var tagName, height,
					position, left, key,
					lineValue, rectValue,
					index, arr

				position = d3.mouse(dom)

				left = position[0] - margin.left - parseInt($(".four").css("margin-left"))

				if (left >= 0 && left <= contentW) {

					arr = getData(left)
					// svg.selectAll(".sinline").style("fill","#919191")
					// d3.select(this).style("fill","#000")

					var index = d3.select(this).attr("data-type")

					var cx = d3.select(svg.selectAll(".circle")[0][index]).attr("cx")
					var cy = d3.select(svg.selectAll(".circle")[0][index]).attr("cy")
					lineWrap.style('display', 'block')

					rect.select(".rectClass").text($(this).attr("data"))
					rect.attr('transform', 'translate(' + (cx - 20) + ',' + -30 + ')')
					line
						.attr('transform', 'translate(' + cx + ',' + 0 + ')')

					circleWrap.selectAll("circle")
						.attr('cx', cx)
						.attr('cy', cy)
				}

			}

			function getData(num) {

				var unitData = contentW / (xAxisData.length - 1),
					preIndex,
					nextIndex, currentIndex, k,
					vaildIndex, y, currentValue, vaildValue, x, b


				var currentIndex = Math.floor(num / unitData)

				if (currentIndex < 0) {

					currentIndex = 0
				}

				if (currentIndex > xAxisData.length - 1) {

					currentIndex = xAxisData.length - 1
				}


				vaildIndex = Math.min(currentIndex + 1, xAxisData.length - 1)



				currentValue = yScale(dataset[currentIndex].value)

				vaildValue = yScale(dataset[vaildIndex].value)

				x = num - (currentIndex * unitData)

				k = 1

				b = currentValue

				y = k * (vaildValue - currentValue) * x / unitData + b

				return [currentIndex, y]
			}



		}

	}

	return {
		singleBrokenLine: singleBrokenLine
	}

})